package com.glr.question.service;

import com.glr.question.dao.OptionDao;
import com.glr.question.entity.Option;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 试题选项业务层
 *
 * @author GLoRy
 * @date 2021/6/11 0:47
 */
@Service
public class OptionService {

    @Autowired
    private OptionDao optionDao;


    /**
     * 新增试题选项
     *
     * @param option 试题选项
     */
    @CachePut(value = "option", key = "#root.methodName")
    @Transactional(rollbackFor = Exception.class)
    public void save(Option option) {
        optionDao.save(option);
    }

    /**
     * 修改试题选项
     *
     * @param option 试题选项实体
     */
     @CachePut(value = "option", key = "#root.methodName")
    @Transactional(rollbackFor = Exception.class)
    public void update(Option option) {
        optionDao.save(option);
    }

    /**
     * 删除试题选项
     *
     * @param id 试题选项id
     */
    @CacheEvict(value = "option", key = "#id")
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        optionDao.deleteById(id);
    }

    /**
     * 根据id查询试题选项
     *
     * @param id 试题选项id
     * @return 试题选项
     */
    @Cacheable(value = "option", key = "#id", unless = "#result eq null")
    public Option findById(Integer id) {
        return optionDao.findById(id).orElse(null);
    }

    /**
     * 查询试题选项
     *
     * @return 试题选项信息
     */
    @Cacheable(value = "option", key = "#root.methodName", unless = "#result eq null")
    public List<Option> findAll() {
        return optionDao.findAll();
    }

    /**
     * 分页查询试题选项
     *
     * @param page     当前页
     * @param pageSize 每页行数
     * @return 试题选项分页信息
     */
    @Cacheable(value = "option", key = "#root.methodName", unless = "#result eq null")
    public Page<Option> findByPage(Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        return optionDao.findAll(pageRequest);
    }
}
